package com.dissertation.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelTarget;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.dissertation.model.Assets;
import com.dissertation.respository.*;
import com.dissertation.service.ExcelService;
import com.dissertation.utils.CompleteRateHelper;
import com.dissertation.utils.ExcelUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
public class ExcelImpl implements ExcelService {


    @Autowired
    private ScientificProjectRepository scientificProjectRepository;

    @Autowired
    private TemplateRepository templateRepository;

    @Autowired
    private AcademicPapersRepository academicPapersRepository;

    @Autowired
    private PatentRepository patentRepository;

    @Autowired
    private TeacherInformationRepository teacherInformationRepository;

    @Autowired
    private WinningRepository winningRepository;

    @Autowired
    private WorkRepository workRepository;

    @Autowired
    private AchievementsRepository achievementsRepository;

    @Autowired
    private AssetsRepository assetsRepository;

    /**
     * 资源导入向导
     * 利用map导入
     * */
    @Override
    public Integer assetsImportGuide(String assetsName, MultipartFile file) {
        try {
            Class<?> clazz = Class.forName("com.dissertation.model."+assetsName);
            ImportParams params = new ImportParams();
            params.setTitleRows(1);
            params.setHeadRows(1);
            List<Map<String,Object>> list = ExcelImportUtil.importExcel(file.getInputStream(),Map.class,params);
            Class superClass = clazz.getSuperclass();
            ExcelTarget excelTarget = clazz.getAnnotation(ExcelTarget.class);
            System.out.println(excelTarget.value());
            Field[] fields = clazz.getDeclaredFields();
            Field[] superFields = superClass.getDeclaredFields();
            fields = ArrayUtils.addAll(fields,superFields);//获取所有的字段，包括父类和本身的字段
            Arrays.stream(fields).forEach(e->{
                if(!e.isAccessible()){
                    e.setAccessible(true);
                }
            });
            List<Assets> resultAssets = new ArrayList<>();//用于存储最后需要保存到数据库中的信息.

            for(Map<String,Object> map:list){
                Assets assets = (Assets) clazz.newInstance();
                for(Field field:fields){
                    Excel excel = field.getAnnotation(Excel.class);
                    List<String> excelValue = null;
                    if(excel!=null){
                        excelValue = Arrays.asList(excel.name().split(","));
                        for (String e : excelValue) {
                            if (e.contains("_".concat(excelTarget.value()))) {
                                e = e.substring(0, e.indexOf("_"));
                            }
                            if (map.keySet().contains(e)) {
                                try {
                                    field.set(assets,ExcelUtil.assignValue(field.getType(),map.get(e)));//为每个字段设值
                                    break;
                                } catch (IllegalAccessException e1) {
                                    e1.printStackTrace();
                                }
                            }
                        }
                    }
                }
                assets.setCompleteRate(CompleteRateHelper.getCompleteRate(assets));
                resultAssets.add(assets);
            }
            assetsRepository.save(resultAssets);
            return resultAssets.size();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


    @Override
    public Integer exportAssetsGuide(String assetsName, List<String> ids, String fileName, HttpServletResponse response, Subject subject) {
        try {
            Class<?> clazz = Class.forName("com.dissertation.model."+assetsName);
            List<Assets> assetsList = assetsRepository.findByIdIn(ids);
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("导出文件(请勿改动此行）","1"),
                    clazz, assetsList);
            writeExcel(workbook,fileName,response);
            return assetsList.size();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }













    /**
     * 生成Excel表
     */

    public void writeExcel(Workbook workbook, String fileName , HttpServletResponse response){
        try {
            //定义excel名称 ISO-8859-1 防止名称乱码
            String msg = new String(
                    (fileName+".xls").getBytes(),"ISO-8859-1");
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename="
                    + msg);
            workbook.write(response.getOutputStream());

        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

